﻿using Lf_Shop.Models;
using Lf_Shop.Models.Database;
using Lf_Shop.service;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Lf_Shop.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class HomeController : ControllerBase
    {
        private readonly Lf_ShopContext _db;
        private readonly IJWTService _jwtService;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="jwtService"></param>
        /// <param name="db"></param>
        public HomeController(IJWTService jwtService, Lf_ShopContext db)
        {
            _jwtService = jwtService;
            _db = db;
        }
        /// <summary>
        /// 获取Token
        /// </summary>
        /// <param name="Uname"></param>
        /// <returns></returns>
        [HttpGet]
        public string CreateToken(string Uname)
        {
            return _jwtService.CreateToken(Uname, 0, "", "","");
        }
        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public string Reg(RegRequest request)
        {
            //保证用户名唯一
            //判断数据（用户名为request.UserName)是否存在
            //查询用户表是否有存在的用户名
            //if (_userService.ExixtUserByUserName(request.UserName))
            //    return "用户存在";

            var user1 = _db.UserBgs.FirstOrDefault(x => x.UserName == request.UserName);
            if (user1!=null)
                return "用户存在";



            //随机字符串
            var salt = new Random().Next(1000, 10000);
            var md5 = MD5Helper.MD5Encrypt32(request.UserPwd + salt);



            var user = new UserBg()
            {
                CreateTime = DateTime.Now,
                UserName = request.UserName,
                UserPhone = request.UserPhone,
                UserPwd = md5,
                UserImg = request.UserImg,
                Salt = salt.ToString()
            };
            _db.UserBgs.Add(user);
            var row = _db.SaveChanges();
            //var row = _userService.AddNewUser(request);
            if (row > 0)
            {
                return "注册成功";
            }
            return "注册失败";
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public string Login(LoginRequest request)
        {
            //第一步 从数据库查询用户为username的用户
            //var user = _db.Users.FirstOrDefault(x => x.UserName == username);

            var user1 = _db.UserBgs.FirstOrDefault(x => x.UserName ==request.UserName);
            //var user = _userService.GetUserByUserName(username);
            //如果不存在用户就不存在
            if (user1 == null)
            {
                return "用户不存在";
            }

            var md5 = MD5Helper.MD5Encrypt32(request.UserPwd + user1.Salt);



            
            if (user1.UserPwd != md5)
            {
                return "密码不正确";
            }
            //如果不相等 返回密码错误
            return _jwtService.CreateToken(user1.UserName, user1.UserId, user1.UserPwd, user1.UserPhone,user1.UserImg);
            //如果相等？？？

            //创建Token 返回token给前端
        }
        /// <summary>
        /// 个人中心
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        public GetUserInfoResponse GetUserInfo()
        {
            //获取用户信息
            var userId = Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value;
            var user = _db.UserBgs.FirstOrDefault(x => x.UserId == Convert.ToInt32(userId));
            if (user == null)
                return null;

            //用户头像，用户昵称
            var response = new GetUserInfoResponse()
            {
                UserName = user.UserName,
                UserPhone = user.UserPhone,
            };
            return response;

        }
        /// <summary>
        /// 修改信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        public string UpdateUserInfo(UpdateUserInfoRequest request)
        {
            //谁的信息  登录用户 Token 
            //谁的信息 登录用户 Token 
            var userId = Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value;
            var user = _db.UserBgs.FirstOrDefault(x => x.UserId == Convert.ToInt32(userId));
            if (user == null)
                return null;

            user.UserName = request.UserName;
            user.UserPhone = request.UserPhone;
            _db.UserBgs.Update(user);

            //保存更改
            var row = _db.SaveChanges();
            if (row > 0)
                return "修改成功";
            return "修改失败";
        }
        

    }
    
}
